﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ConfigHelper.Models;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Windows;
using Microsoft.Extensions.Logging;

namespace ConfigHelper.ViewModels
{
    public partial class MainViewModel : ObservableObject
    {
        private readonly string _configPath;

        private readonly ILogger<MainViewModel> _log;

        [ObservableProperty]
        RootParam _rootParamProp;

        public MainViewModel(IOptionsSnapshot<RootParam> optionsSnapshot, ILogger<MainViewModel> log)
        {
            RootParamProp = optionsSnapshot.Value;
            _log = log;
            init();
        }

        private void init()
        {
            _log.LogError("报错了哦宝贝、快来改bug");
        }

        [RelayCommand]
        private void SaveParam()
        {
            try
            {
                // 项目中的配置文件路径
                 string _projectConfigPath = Path.Combine(
                    Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName,
                    "Configs",
                    "appsettings.json"
                );
                // 创建配置构建器
                var configuration = new ConfigurationBuilder()
                    .SetBasePath(Environment.CurrentDirectory + "\\Configs")
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .Build();

                // 获取完整的配置并更新需要修改的部分
                var root = new RootParam();
                configuration.Bind(root);
                root.SystemParam = RootParamProp.SystemParam;
                root.PlcParam = RootParamProp.PlcParam;

                // 序列化配置
                var json = System.Text.Json.JsonSerializer.Serialize(root, new System.Text.Json.JsonSerializerOptions 
                { 
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });

                // 修改项目中Configs的配置文件就行了、运行目录下的Config文件会自动复制
                File.WriteAllText(_projectConfigPath, json);   // 更新项目配置

                MessageBox.Show("参数保存成功！", "提示");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存参数失败：{ex.Message}", "错误");
            }
        }
    }
}
